package com.xuedongzhilian.controller;

import com.xuedongzhilian.dto.Result;
import com.xuedongzhilian.entity.Message;
import com.xuedongzhilian.service.IMessageService;
import com.xuedongzhilian.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 消息推送控制器
 * </p>
 *
 * @author 学动智联团队
 * @since 2025-10-14
 */
@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {

    @Resource
    private IMessageService messageService;

    /**
     * 获取用户消息列表
     */
    @GetMapping
    public Result getUserMessages(@RequestParam(required = false) Integer type,
                                  @RequestParam(defaultValue = "1") Integer current,
                                  @RequestParam(defaultValue = "10") Integer size) {
        Long userId = UserHolder.getUser().getId();
        
        List<Message> messages = messageService.lambdaQuery()
                .eq(Message::getUserId, userId)
                .eq(type != null, Message::getType, type)
                .orderByDesc(Message::getCreateTime)
                .page(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, size))
                .getRecords();
                
        return Result.ok(messages);
    }

    /**
     * 获取未读消息数量
     */
    @GetMapping("/unread-count")
    public Result getUnreadMessageCount(@RequestParam(required = false) Integer type) {
        Long userId = UserHolder.getUser().getId();
        
        Integer count = messageService.lambdaQuery()
                .eq(Message::getUserId, userId)
                .eq(Message::getIsRead, 0)
                .eq(type != null, Message::getType, type)
                .count();
                
        return Result.ok(count);
    }

    /**
     * 标记消息为已读
     */
    @PutMapping("/read/{id}")
    public Result markMessageAsRead(@PathVariable Long id) {
        Long userId = UserHolder.getUser().getId();
        Message message = messageService.getById(id);
        
        if (message == null) {
            return Result.fail("消息不存在");
        }
        
        if (!message.getUserId().equals(userId)) {
            return Result.fail("无权操作该消息");
        }
        
        if (message.getIsRead() == 1) {
            return Result.ok("消息已读");
        }
        
        message.setIsRead(1);
        message.setReadTime(LocalDateTime.now());
        message.setUpdateTime(LocalDateTime.now());
        
        boolean success = messageService.updateById(message);
        if (success) {
            return Result.ok("标记成功");
        } else {
            return Result.fail("标记失败");
        }
    }

    /**
     * 批量标记消息为已读
     */
    @PutMapping("/read-batch")
    public Result markMessagesAsRead(@RequestBody List<Long> messageIds) {
        Long userId = UserHolder.getUser().getId();
        
        List<Message> messages = messageService.listByIds(messageIds);
        for (Message message : messages) {
            if (message.getUserId().equals(userId) && message.getIsRead() == 0) {
                message.setIsRead(1);
                message.setReadTime(LocalDateTime.now());
                message.setUpdateTime(LocalDateTime.now());
            }
        }
        
        boolean success = messageService.updateBatchById(messages);
        if (success) {
            return Result.ok("批量标记成功");
        } else {
            return Result.fail("批量标记失败");
        }
    }

    /**
     * 删除消息
     */
    @DeleteMapping("/{id}")
    public Result deleteMessage(@PathVariable Long id) {
        Long userId = UserHolder.getUser().getId();
        Message message = messageService.getById(id);
        
        if (message == null) {
            return Result.fail("消息不存在");
        }
        
        if (!message.getUserId().equals(userId)) {
            return Result.fail("无权操作该消息");
        }
        
        boolean success = messageService.removeById(id);
        if (success) {
            return Result.ok("删除成功");
        } else {
            return Result.fail("删除失败");
        }
    }

    /**
     * 发送系统消息（测试用）
     */
    @PostMapping("/send")
    public Result sendMessage(@RequestBody Message message) {
        message.setUserId(UserHolder.getUser().getId());
        message.setCreateTime(LocalDateTime.now());
        message.setUpdateTime(LocalDateTime.now());
        
        boolean success = messageService.save(message);
        if (success) {
            return Result.ok(message);
        } else {
            return Result.fail("发送失败");
        }
    }
}